package com.work.farm.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.work.entity.PageResult;
import com.work.entity.Result;
import com.work.entity.StatusCode;
import com.work.farm.pojo.TCustFarmEntity;
import com.work.farm.service.FarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/farm")
public class FarmController {

    @Autowired
    private FarmService farmService;

    //添加农场片区
    @PostMapping("/add")
    public Result addFarm(@RequestBody TCustFarmEntity tCustFarmEntity){
        try{
            System.out.println(tCustFarmEntity.toString());
            List<String> pos = tCustFarmEntity.getPos();
            String s = JSON.toJSONString(pos);
            tCustFarmEntity.setPosition(s);
            //调用
            farmService.addFarm(tCustFarmEntity);
            return new Result(true,StatusCode.ADD_OK,"");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.ADD_ERROR,"");
        }
    }

    //修改农场片区
    @PutMapping("/updateFarm")
    public Result updateFarm(@RequestBody TCustFarmEntity tCustFarmEntity){
        try{
            //调用
            farmService.updateFarm(tCustFarmEntity);
            return new Result(true,StatusCode.UPDATE_Ok,"修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.UPDATE_ERROR,"修改失败");
        }
    }

    //分页查询农场片区信息
    @GetMapping("/findByPage")
    public Result findByPage(@RequestParam(value = "pageNum",defaultValue = "1",required = false)Integer pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "5",required = false)Integer pageSize,
                             @RequestParam(required = false) Map searchMap){
        try{
            Page<TCustFarmEntity> page = farmService.findByPage(pageNum, pageSize, searchMap);
            PageResult<TCustFarmEntity> pageResult = new PageResult<>(page.getTotal(), page.getResult());
            return new Result(true,StatusCode.FIND_Ok,"查询成功",pageResult);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true,StatusCode.FIND_ERROR,"查询失败");
        }
    }

    @GetMapping("/findById")
    public Result findById(@RequestParam("id")Integer id){
        try{
            TCustFarmEntity tCustFarmEntity = farmService.findById(id);
            return new Result(true,StatusCode.FIND_Ok,"查询成功",tCustFarmEntity);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true,StatusCode.FIND_ERROR,"查询失败");
        }
    }


}

